package interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangjie
 */
public class MyCountDownLatch {

  private volatile int count;

  private ReentrantLock reentrantLock;
  private Condition condition;

  public MyCountDownLatch(int count) {
    reentrantLock = new ReentrantLock();
    condition = reentrantLock.newCondition();
    this.count = count;
  }

  public void countDown() {
    reentrantLock.lock();
    try {
      count--;
      if (count == 0) {
        condition.signalAll();
      }
    } finally {
      reentrantLock.unlock();
    }

  }

  public void await() throws InterruptedException {
    reentrantLock.lock();
    try {
      if (count != 0) {
        condition.await();
      }
    } finally {
      reentrantLock.unlock();
    }
  }

  public static void main(String[] args) throws InterruptedException {
    MyCountDownLatch myCountDownLatch = new MyCountDownLatch(10);
    for (int i = 0; i < 10; i++) {
      int finalI = i;
      new Thread(() -> {
        try {
          Thread.sleep(10);
          System.out.println("线程" + finalI);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          myCountDownLatch.countDown();
        }

      }).start();
    }
    System.out.println("等待");
    myCountDownLatch.await();
    System.out.println("结束");
  }

}
